package org.example.register;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import org.example.common.Url;
import redis.clients.jedis.Jedis;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MapRegister {
    private static Map<String, List<Url>> map = new HashMap<>();

    public static void register(String interfaceName, Url url) {
        List<Url> urls = map.get(interfaceName);
        if (urls == null) {
            urls = new ArrayList<>();
        }
        urls.add(url);
        //存到redis中
        putKey(interfaceName, urls);
    }

    public static List<Url> get(String interfaceName) {
        Jedis jedis = new Jedis("47.102.44.15", 6379);
        jedis.auth("000415");

        //选择指定redis数据库号
        jedis.select(0);
        String s = jedis.get(interfaceName);
        List<Url> urls = new Gson().fromJson(s,new TypeToken<List<Url>>(){}.getType());
        return urls;
    }


    public static void putKey(String interfaceName, List<Url> url) {
        //连接Redis--->必须保证你的Redis服务运行远程连接
        Jedis jedis = new Jedis("47.102.44.15", 6379);
        jedis.auth("000415");

        //选择指定redis数据库号
        jedis.select(0);

        String asJsonArray = new Gson().toJsonTree(url).getAsJsonArray().toString();

        //添加数据
        jedis.set(interfaceName, asJsonArray);
        //资源关闭
        jedis.close();
    }

}
